package com.ruoyi.web.controller.wx;

import com.alibaba.fastjson2.JSONObject;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ByBs;
import com.ruoyi.system.domain.ByOrder;
import com.ruoyi.system.domain.ByOrderPayLog;
import com.ruoyi.system.mapper.ByOrderPayLogMapper;
import com.ruoyi.system.service.IByBsService;
import com.ruoyi.system.service.IByJzService;
import com.ruoyi.system.service.IByOrderService;
import com.ruoyi.web.core.config.Paypal.PaypalPaymentIntent;
import com.ruoyi.web.core.config.Paypal.PaypalPaymentMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx/order")
@Validated
public class WxOderController {
    @Autowired
    private IByOrderService orderService;

    @Autowired
    private IByJzService jzService;

    @Autowired
    private IByBsService bsService;

    @Autowired
    private APIContext apiContext;

    @Autowired
    private ByOrderPayLogMapper orderPayLogMapper;

    @Value("${pay.paypal.PAYPAL_SUCCESS_PAGE}")
    private String PAYPAL_SUCCESS_PAGE;
    @Value("${pay.paypal.PAYPAL_CANCEL_PAGE}")
    private String PAYPAL_CANCEL_PAGE;

    @Value("${pay.paypal.PAYPAL_SUCCESS_URL}")
    private String PAYPAL_SUCCESS_URL;

    @Value("${pay.paypal.PAYPAL_CANCEL_URL}")
    private String PAYPAL_CANCEL_URL;





    @PostMapping("queryOrderDetail")
    public AjaxResult queryOrderDetail(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        JSONObject orderEntity = orderService.orderDetailForidAndUserid(json);
        if(orderEntity == null){
            return AjaxResult.success();
        }
        JSONObject bsEntity = bsService.bsDetailById(orderEntity.getString("bs_id"));


        Map map = new HashMap();
        map.put("order",orderEntity);
        map.put("bs",bsEntity);

        return AjaxResult.success(map);
    }

    @PostMapping("getBsEvalById")
    public AjaxResult getBsEvalById(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        List<JSONObject> list = orderService.getBsEvalById(json);
        return AjaxResult.success(list);
    }


    @PostMapping("wxPayOrderMM")
    public AjaxResult wxPayOrderMM(@RequestBody String param, HttpServletRequest request){
        JSONObject json = JSONObject.parseObject(param);
        Object obj = orderService.payPayOrder(json,request);
        return AjaxResult.success(obj);
    }

    /**
     * 进行开启或者停止计时的任务
     * @param param
     * @return
     */
    @PostMapping("orderDetailById")
    public AjaxResult orderDetailById(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        Object obj = orderService.orderDetailById(json);
        return AjaxResult.success(obj);
    }

    /**
     * 进行开启或者停止计时的任务
     * @param param
     * @return
     */
    @PostMapping("orderTimeMananger")
    public AjaxResult orderTimeMananger(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        Object obj = orderService.orderTimeMananger(json);
        return AjaxResult.success(obj);
    }

    /**
     * 判断开始或结束计时
     * @return
     */
    @PostMapping("isStartOrEnd")
    public AjaxResult isStartOrEnd(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        String orderid = json.getString("orderid");
        String status = orderService.isStartOrEnd(orderid);
        if ("3".equals(status)){
            JSONObject start = new JSONObject();
            start.put("result","开始");
            return AjaxResult.success(start);
        }else if ("4".equals(status)){
            JSONObject end = new JSONObject();
            end.put("result","结束");
            return AjaxResult.success(end);
        }else {
            return AjaxResult.error("当前状态暂不支持~");
        }
    }

    @PostMapping("saveOrderEval")
    public Object saveOrderEval(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        Object obj = orderService.saveOrderEval(json);
        return AjaxResult.success(obj);
    }


    @PostMapping("pay-notify")
    public Object payNotify(HttpServletRequest request, HttpServletResponse response) {
        return orderService.payNotify(request, response);
    }


    @PostMapping("payPayOrder")
    public Object payPayOrder(@RequestBody String param, HttpServletRequest request){
        JSONObject json = JSONObject.parseObject(param);
        Object obj = orderService.payPayOrder(json, request);
        return AjaxResult.success(obj);
    }


    @PostMapping("payDjOrder")
    public Object payDjOrder(@RequestBody String param, HttpServletRequest request){
        JSONObject json = JSONObject.parseObject(param);
        Object obj = orderService.prepay(json, request);
        return AjaxResult.success(obj);
    }


    @PostMapping("quitOrder")
    public Object quitOrder(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        orderService.quitOrder(json);
        return AjaxResult.success();
    }

    @PostMapping("saveEntity")
    public Object saveEntity(@RequestBody String param, HttpServletRequest request){
        JSONObject json = JSONObject.parseObject(param);
//        String wxid = json.getString("wxid");
//        String bsid = json.getString("bsid"); // 商品id

        JSONObject addrDetail = jzService.getDetailBywxid(json);

        JSONObject resultJson = new JSONObject();
        if(addrDetail == null){
            resultJson.put("code","400");
            resultJson.put("msg","Please maintain the delivery address!");
            return AjaxResult.success(resultJson);
        }else{
            orderService.savaJzWxOrder(json);
            // 进行获取用户信息
            String wxid = json.getString("wxid");
            JSONObject orderEntity = orderService.orderDetailByUserid(wxid);
            resultJson.put("code","200");
            resultJson.put("msg",orderEntity);
            return AjaxResult.success(resultJson);
        }
       /* orderService.savaJzWxOrder(json);// 进行保存订单信息
        // 进行获取订单信息
        String wxid = json.getString("wxid");
        ByOrder entity = orderService.getOrderByWxId(wxid);
        if(StringUtils.isEmpty(entity.getBsId())){
            return AjaxResult.error("400","获取订单错误");
        }
        json.put("id",entity.getId());

        Object obj = orderService.prepay(json, request);*/

    }


    @PostMapping("getOrderByWxid")
    public Object getOrderByWxid(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        String code = json.getString("code");
        if(StringUtils.isEmpty(code)){
            return AjaxResult.success();
        }
        List<JSONObject> list = orderService.getOrderByWxid(json);

        return AjaxResult.success(list);
    }


    @PostMapping("startOrder")
    public Object startOrder(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        orderService.startOrder(json);
        return AjaxResult.success();
    }

    @PostMapping("stopOrder")
    public Object stopOrder(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        orderService.stopOrder(json);
        return AjaxResult.success();
    }

    @PostMapping("delDjOrder")
    public Object delDjOrder(@RequestBody String param){
        JSONObject json = JSONObject.parseObject(param);
        Long ids = json.getLong("id");
        orderService.deleteByOrderById(ids);

        return AjaxResult.success();
    }



    @PostMapping("/payPal")
    public Object toPay(@RequestBody String param){
        // System.out.println(param);
        JSONObject json = JSONObject.parseObject(param);
        String orderid = json.getString("orderid");
        String userid = json.getString("userid");
        ByOrder order = orderService.selectByOrderById(Long.parseLong(orderid));
        ByBs bs = bsService.selectByBsById(Long.parseLong(order.getBsId()));
        Map map = new HashMap();


//        BigDecimal payAmount = new BigDecimal(1);
        BigDecimal payAmount = order.getPayprice();//new BigDecimal(order.getPayprice());
        try {
            Payment payment = createPayment(
                    payAmount,
                    "USD",
                    PaypalPaymentMethod.paypal,
                    PaypalPaymentIntent.sale,
                    bs.getName(),//"购买商品信息~"
                    PAYPAL_CANCEL_URL,
                    PAYPAL_SUCCESS_URL);
//            System.out.println(payment.toString());
//            log.info("=========================================");
//            log.info(payment.toString());
//            log.info("=========================================");
//            //保存paypal预支付信息
//            //修改订单金额 & 支付的流水号
//            log.info("支付金额："+payAmount);
//            log.info("订单号："+payment.getId());  // ysxm
            order.setRemark(payment.getId());
            orderService.updateByOrder(order);
            ByOrderPayLog orderPayLog = new ByOrderPayLog();
            orderPayLog.setOrderSn(payment.getId());
            orderPayLog.setPrice(order.getPayprice()+"");
            orderPayLog.setStatus("0");
            orderPayLog.setAddtime(DateUtils.getTime());
            orderPayLog.setOrderId(orderid);
            orderPayLog.setWxId(userid);

            orderPayLogMapper.insertByOrderPayLog(orderPayLog);
            for (Links links : payment.getLinks()) {
                if (links.getRel().equals("approval_url")) {
                    // System.out.println(links.getHref());
                    // return AjaxResult.success(links.getHref());// links.getHref();
                    map.put("url",links.getHref());
                    break;
                }
            }
        } catch (PayPalRESTException e) {
            //保存paypal预支付异常信息 .......
            // log.error(e.getMessage());
        }


        return AjaxResult.success(map);
    }


    public Payment createPayment(BigDecimal total, String currency, PaypalPaymentMethod method, PaypalPaymentIntent intent,
                                 String description, String cancelUrl, String successUrl) throws PayPalRESTException {
        Amount amount = new Amount();
        amount.setCurrency(currency);
        amount.setTotal(String.format("%.2f", total));

        Transaction transaction = new Transaction();
        transaction.setDescription(description);
        transaction.setAmount(amount);

        List<Transaction> transactions = new ArrayList<>();
        transactions.add(transaction);

        Payer payer = new Payer();
        payer.setPaymentMethod(method.toString());

        Payment payment = new Payment();
        payment.setIntent(intent.toString());
        payment.setPayer(payer);
        payment.setTransactions(transactions);
        RedirectUrls redirectUrls = new RedirectUrls();
        redirectUrls.setCancelUrl(cancelUrl);
        redirectUrls.setReturnUrl(successUrl);
        payment.setRedirectUrls(redirectUrls);

        return payment.create(apiContext);
    }

}
